package com.livableindex.service;

import com.livableindex.entity.WeatherData;
import com.livableindex.repository.WeatherDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class WeatherDataService {
    
    @Autowired
    private WeatherDataRepository weatherDataRepository;
    
    public List<WeatherData> getWeatherDataByDistrict(String province, String city, String district) {
        return weatherDataRepository.findByProvinceAndCityAndDistrictOrderByDateAsc(province, city, district);
    }
    
    public List<WeatherData> getWeatherDataByCity(String province, String city) {
        return weatherDataRepository.findByProvinceAndCityOrderByDateAsc(province, city);
    }
    
    public List<WeatherData> getWeatherDataByProvince(String province) {
        return weatherDataRepository.findByProvinceOrderByDateAsc(province);
    }
    
    public List<String> getAllProvinces() {
        return weatherDataRepository.findAllProvinces();
    }
    
    public List<String> getCitiesByProvince(String province) {
        return weatherDataRepository.findCitiesByProvince(province);
    }
    
    public List<String> getDistrictsByProvinceAndCity(String province, String city) {
        return weatherDataRepository.findDistrictsByProvinceAndCity(province, city);
    }
    
    public Double calculateLivableIndex(String province, String city, String district) {
        return weatherDataRepository.calculateAverageLivableIndex(province, city, district);
    }
    
    public WeatherData saveWeatherData(WeatherData weatherData) {
        // 计算宜居指数
        weatherData.setLivableIndex(calculateLivableScore(weatherData));
        return weatherDataRepository.save(weatherData);
    }
    
    private Double calculateLivableScore(WeatherData data) {
        // 简化的宜居指数计算算法
        double score = 100.0;
        
        // AQI影响（0-50:优, 51-100:良, 101-150:轻度污染, 151+:中度污染及以上）
        if (data.getAqi() <= 50) {
            score -= 0;
        } else if (data.getAqi() <= 100) {
            score -= 10;
        } else if (data.getAqi() <= 150) {
            score -= 25;
        } else {
            score -= 40;
        }
        
        // PM2.5影响
        if (data.getPm25() > 75) {
            score -= 20;
        } else if (data.getPm25() > 35) {
            score -= 10;
        }
        
        // 温度适宜度（15-25°C为最佳）
        double tempDiff = Math.abs(data.getTemperature() - 20);
        if (tempDiff > 10) {
            score -= 15;
        } else if (tempDiff > 5) {
            score -= 5;
        }
        
        // 湿度适宜度（40-60%为最佳）
        double humidityDiff = Math.abs(data.getHumidity() - 50);
        if (humidityDiff > 20) {
            score -= 10;
        } else if (humidityDiff > 10) {
            score -= 5;
        }
        
        return Math.max(0, Math.min(100, score));
    }
}
